package com.yzxb.messystem.service.impl;

import com.yzxb.messystem.entity.WorkOrder;
import com.yzxb.messystem.exception.BusinessException;
import com.yzxb.messystem.exception.ResourceNotFoundException;
import com.yzxb.messystem.mapper.WorkOrderMapper;
import com.yzxb.messystem.service.WorkOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class WorkOrderServiceImpl implements WorkOrderService {
    
    @Autowired
    private WorkOrderMapper workOrderMapper;
    
    @Override
    public List<WorkOrder> getAllWorkOrders() {
        return workOrderMapper.selectList(null);
    }
    
    @Override
    public Optional<WorkOrder> getWorkOrderById(Long id) {
        WorkOrder workOrder = workOrderMapper.selectById(id);
        return Optional.ofNullable(workOrder);
    }
    
    @Override
    public Optional<WorkOrder> getWorkOrderByCode(String orderCode) {
        WorkOrder workOrder = workOrderMapper.findByOrderCode(orderCode);
        return Optional.ofNullable(workOrder);
    }
    
    @Override
    public WorkOrder addWorkOrder(WorkOrder workOrder) {
        // 检查工单编码是否已存在
        if (workOrderMapper.existsByOrderCode(workOrder.getOrderCode()) > 0) {
            throw new BusinessException("工单编码已存在: " + workOrder.getOrderCode());
        }
        // 设置创建时间
        workOrder.setCreateTimeDefault();
        workOrderMapper.insert(workOrder);
        return workOrder;
    }
    
    @Override
    public WorkOrder updateWorkOrder(Long id, WorkOrder workOrder) {
        // 检查工单是否存在
        WorkOrder existingWorkOrder = workOrderMapper.selectById(id);
        if (existingWorkOrder == null) {
            throw new ResourceNotFoundException("WorkOrder", "id", id);
        }
        
        // 更新工单信息
        existingWorkOrder.setProductId(workOrder.getProductId());
        existingWorkOrder.setPlannedQuantity(workOrder.getPlannedQuantity());
        existingWorkOrder.setCompletedQuantity(workOrder.getCompletedQuantity());
        existingWorkOrder.setRejectedQuantity(workOrder.getRejectedQuantity());
        existingWorkOrder.setStatus(workOrder.getStatus());
        existingWorkOrder.setPlannedStartDate(workOrder.getPlannedStartDate());
        existingWorkOrder.setPlannedEndDate(workOrder.getPlannedEndDate());
        existingWorkOrder.setActualStartDate(workOrder.getActualStartDate());
        existingWorkOrder.setActualEndDate(workOrder.getActualEndDate());
        existingWorkOrder.setProductionLine(workOrder.getProductionLine());
        existingWorkOrder.setRemarks(workOrder.getRemarks());
        // 设置更新时间
        existingWorkOrder.setUpdateTimeDefault();
        
        workOrderMapper.updateById(existingWorkOrder);
        return existingWorkOrder;
    }
    
    @Override
    public void deleteWorkOrder(Long id) {
        // 检查工单是否存在
        if (workOrderMapper.selectById(id) == null) {
            throw new ResourceNotFoundException("WorkOrder", "id", id);
        }
        workOrderMapper.deleteById(id);
    }
    
    @Override
    public List<WorkOrder> getWorkOrdersByStatus(WorkOrder.OrderStatus status) {
        return workOrderMapper.findByStatus(status);
    }
    
    @Override
    public List<WorkOrder> getWorkOrdersByProductionLine(String productionLine) {
        return workOrderMapper.findByProductionLine(productionLine);
    }
    
    @Override
    public List<WorkOrder> getWorkOrdersByProductId(Long productId) {
        return workOrderMapper.findByProductId(productId);
    }
    
    @Override
    public List<WorkOrder> getWorkOrdersByDateRange(LocalDateTime startDate, LocalDateTime endDate) {
        return workOrderMapper.findByPlannedStartDateBetween(startDate, endDate);
    }
    
    @Override
    public WorkOrder changeWorkOrderStatus(Long id, WorkOrder.OrderStatus status) {
        // 检查工单是否存在
        WorkOrder workOrder = workOrderMapper.selectById(id);
        if (workOrder == null) {
            throw new ResourceNotFoundException("WorkOrder", "id", id);
        }
        
        // 更新状态
        workOrder.setStatus(status);
        // 设置更新时间
        workOrder.setUpdateTimeDefault();
        
        // 根据状态变化更新其他字段
        if (status == WorkOrder.OrderStatus.IN_PROGRESS && workOrder.getActualStartDate() == null) {
            workOrder.setActualStartDate(LocalDateTime.now());
        } else if (status == WorkOrder.OrderStatus.COMPLETED && workOrder.getActualEndDate() == null) {
            workOrder.setActualEndDate(LocalDateTime.now());
        }
        
        workOrderMapper.updateById(workOrder);
        return workOrder;
    }
    
    @Override
    public WorkOrder updateWorkOrderQuantities(Long id, Integer completedQuantity, Integer rejectedQuantity) {
        // 检查工单是否存在
        WorkOrder workOrder = workOrderMapper.selectById(id);
        if (workOrder == null) {
            throw new ResourceNotFoundException("WorkOrder", "id", id);
        }
        
        // 更新数量
        if (completedQuantity != null) {
            workOrder.setCompletedQuantity(completedQuantity);
        }
        if (rejectedQuantity != null) {
            workOrder.setRejectedQuantity(rejectedQuantity);
        }
        // 设置更新时间
        workOrder.setUpdateTimeDefault();
        
        // 如果完成数量达到计划数量，自动将状态设置为已完成
        if (workOrder.getCompletedQuantity() >= workOrder.getPlannedQuantity() && 
            workOrder.getStatus() != WorkOrder.OrderStatus.COMPLETED && 
            workOrder.getStatus() != WorkOrder.OrderStatus.CANCELLED) {
            workOrder.setStatus(WorkOrder.OrderStatus.COMPLETED);
            if (workOrder.getActualEndDate() == null) {
                workOrder.setActualEndDate(LocalDateTime.now());
            }
        }
        
        workOrderMapper.updateWorkOrderQuantities(workOrder.getId(), workOrder.getCompletedQuantity(), workOrder.getRejectedQuantity());
        return workOrder;
    }
}